using System.Configuration;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NUnit.Framework;
using UserManagement.Dal.NH.Mappings;

namespace UserManagement.DomainEntity.Tests.MappingTests
{
    public class FixtureBase
    {
        private SessionSource _sessionSource;
        private string _defaultTestingConnectionString;

        protected ISession Session { get; private set; }

        [SetUp]
        public void SetupContext()
        {
            _defaultTestingConnectionString = "connectionStringKeySQL2008";
            BeforeEachTest();
        }

        [TearDown]
        public void TearDownContext()
        {
            AfterEachTest();
        }

        protected virtual void BeforeEachTest()
        {
            var conns = ConfigurationManager.ConnectionStrings;
            if (conns != null && conns.Count > 1)
            {
                ConnectionStringSettings conset = conns[_defaultTestingConnectionString];
                NHibernate.Cfg.Configuration config = null;
                switch (_defaultTestingConnectionString)
                {
                    case "connectionStringKeySQL2008":
                        if (!string.IsNullOrEmpty(conset.ConnectionString))
                        {
                            config = MsSqlConfiguration.MsSql2008.ConnectionString(conset.ConnectionString)
                                .UseReflectionOptimizer()
                                .ShowSql()
                                .ConfigureProperties(new NHibernate.Cfg.Configuration());
                        }
                        break;
                    case "connectionStringKeySQLite":
                        if (!string.IsNullOrEmpty(conset.ConnectionString))
                        {
                            config = SQLiteConfiguration.Standard.ConnectionString(conset.ConnectionString)
                                .UseReflectionOptimizer()
                                .ShowSql()
                                .ConfigureProperties(new NHibernate.Cfg.Configuration());
                        }
                        break;
                }
                _sessionSource = new SessionSource(new TestModel(), config);
                Session = _sessionSource.CreateSession();
                //_sessionSource.BuildSchema(Session);
                CreateInitialData(Session);
                Session.Clear();
            }
        }

        protected virtual void AfterEachTest()
        {
            Session.Clear();
            Session.Dispose();
        }

        protected virtual void CreateInitialData(ISession session)
        {
        }
    }
}